import { _decorator, Component, Node, Sprite, SpriteAtlas, SpriteFrame, UITransform } from 'cc';
import { PlayerTemplate } from './PlayerTemplate';
import { Card } from './Card';
import { StackCards } from './StackCards';
import { CardTemplate } from './CardTemplate';
import { InitCards } from './InitCards';
import DataManager from './global/DataManager';
import { ISeat } from './common';
import { EventEnum } from './Enum';
import EventManager from './manages/EventManager';
const { ccclass, property } = _decorator;

@ccclass('Seat')
export class Seat extends Component {
    @property
    direction: number; // 0东1西2南3北 
    isCatchCardStack: boolean; // 当前是否为被抓牌的方位
    catchCardIndex: number = 35; //当前开始抓取的索引 
    isCatchFlowerCardStackIndex: boolean;  // 当前是否为被补花的方位
    catchFlowerCardIndex: boolean; // 当前开始补花的索引
    player: PlayerTemplate;
    isLastWinner: boolean; // 上一次的胜利者
    fristCatchFlower: boolean = false;

    handCardCount: number = 14;  //当前手牌数量  
    private hasGradCard: boolean = true; // 回合开始时是时候抓牌 回合开始前为false 结束改为true 遇到 吃 碰 杠 开始为true
    isMyTurn: boolean = false;  // 当前是否为自己的回合 
    hand: Node;
    used: Node;
    head: Node;
    action: Node;
    id: number;


    init(data: ISeat) {
        this.direction = data.dirction
        this.id = data.id
    }

    onLoad(): void {
        this.hand = this.node.getChildByName("hand")
        this.used = this.node.getChildByName("used")
        this.head = this.node.getChildByName("head")
        this.action = this.node.getChildByName("action")

    }




    // 自己回合发生的动作 
    async roundAction() {
        this.isMyTurn = true
        //  不满足手牌数量时 抓牌
        if (!this.hasGradCard) {
            this.grabHandCard()
        }
        // 如果没有第一次补花 先补花
        if (!this.fristCatchFlower) {
            await this.makeFristCatchFlower()
        }

    }

    async makeFristCatchFlower() {
        const flowerCount = this.node.getChildByName("action").children.length
        for (let index = 0; index < flowerCount; index++) {
            await this.makeCatchFlower()
        }
    }

    async makeCatchFlower() {
        return new Promise<void>((resolve, reject) => {
            setTimeout(() => {
                // const sceenNode: Node = this.node.getParent();
                // const initCards = sceenNode.getComponent(InitCards)
                const mm = DataManager.Instance.mm
                let index: number;
                // let catchFlowerCardStackIndex: number;
                if ((mm.catchFlowerCardIndex % 2) != 0) {
                    if (mm.catchFlowerCardIndex + 2 >= 37) {
                        index = 1
                        // catchFlowerCardStackIndex = (mm.catchFlowerCardStackIndex + 5) % 4
                    } else {
                        index = mm.catchFlowerCardIndex + 2
                        // catchFlowerCardStackIndex = mm.catchFlowerCardStackIndex
                    }
                } else {
                    index = mm.catchFlowerCardIndex
                    // catchFlowerCardStackIndex = mm.catchFlowerCardStackIndex
                }
                // 抓取的牌堆
                // const catchCardStack = mm.children[catchFlowerCardStackIndex].getChildByName("stack")

                const seatId = mm.seats[mm.catchFlowerCardStackIndex].id

                const catchCardStack = this.node.getParent().children.find(e => {
                    if (e.getComponent(Seat) && e.getComponent(Seat).id == seatId) {
                        return e;
                    }
                }).getChildByName("head")

                // console.log(index, mm.seats.find(e => e.dirction == catchFlowerCardStackIndex));
                // 抓取的牌


                const catchCard = catchCardStack.children[index]
                // console.log(catchCardStack, catchCardStack.children[index]);
                // console.log(catchCard, index);
                const hand = this.node.getChildByName("hand")
                const newNode = new Node("");
                const ui = catchCard.getComponent(UITransform)
                newNode.addComponent(UITransform);
                newNode.getComponent(UITransform).width = ui.width
                newNode.getComponent(UITransform).height = ui.height
                catchCardStack.insertChild(newNode, index)
                catchCard.setParent(hand)
                mm.catchFlowerCardIndex++
                if (mm.catchFlowerCardIndex == 36) {
                    mm.catchFlowerCardIndex = 0
                    mm.catchFlowerCardStackIndex = (mm.catchFlowerCardStackIndex + 5) % 4
                }
                const cardTemplate: CardTemplate = catchCard.getComponent(CardTemplate)
              

                cardTemplate.state = 1
                if (mm.currentActiveDirection >= DataManager.Instance.myDirction) {
                    cardTemplate.directionInFrist = DataManager.Instance.myDirction - mm.currentActiveDirection
                } else {
                    cardTemplate.directionInFrist = 4 - (DataManager.Instance.myDirction - mm.currentActiveDirection)
                }
                cardTemplate.updateCardSpriteFrame()
                if (cardTemplate.type == 'zhongfabai' || cardTemplate.getComponent(CardTemplate).type == 'hongheihua') {
                    cardTemplate.state = 3
                    const action = this.node.getChildByName("action")
                    catchCard.setParent(action)
                    cardTemplate.updateCardSpriteFrame()
                    this.makeCatchFlower()

                }

                resolve()
            }, 500)
        })
    }


    // 更新手牌
    updateHandCardNode() {


    }
    //  每回合开始抓牌阶段
    initHandCardNode() {

    }
    //  
    /** 抓牌 
     *  1. 回个开始时每次抓四张
     *  2. 抓到第四圈时 头家抓两张 其余抓一张
     *  3. 正常阶段每次抓一张
     * 
     * 
     */
    grabHandCard() {
        const mm = DataManager.Instance.mm
        const seatId = mm.seats[mm.catchCardStackIndex].id

        const startStack = this.node.getParent().children.find(e => {
            if (e.getComponent(Seat) && e.getComponent(Seat).id == seatId) {
                return e;
            }
        }).getChildByName("head")


        // .getChildByName("head")

        const node = [...startStack.children][mm.catchCardIndex]
        const cardTemplate: CardTemplate = node.getComponent(CardTemplate)
        cardTemplate.state = 1
        cardTemplate.directionInFrist = this.direction + 3 - DataManager.Instance.myDirction
        if (this.direction >= DataManager.Instance.myDirction) {
            cardTemplate.directionInFrist = DataManager.Instance.myDirction - this.direction
        } else {
            cardTemplate.directionInFrist = 4 - (DataManager.Instance.myDirction - this.direction)
        }
        node.setParent(this.node.getChildByName("hand"))
        const newNode = new Node("")
        const ui = node.getComponent(UITransform)
        newNode.addComponent(UITransform);
        newNode.getComponent(UITransform).width = ui.width
        newNode.getComponent(UITransform).height = ui.height
        startStack.insertChild(newNode, DataManager.Instance.mm.catchCardIndex)

        cardTemplate.updateCardSpriteFrame()

        mm.catchCardIndex--;
        if (mm.catchCardIndex == -1) {
            mm.catchCardIndex = 35
            mm.catchCardStackIndex = (mm.catchCardStackIndex + 3) % 4
            if (mm.catchCardStackIndex == 4) {
                mm.catchCardStackIndex = 0
            }
        }
    }



    updateStackCardNode() {

    }

    update(deltaTime: number) {
        // console.log(this.stackCards, "stackCards");
    }
}


